package com.product.system.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.product.system.domain.response.SysRole;
import com.product.system.service.SysRoleService;

import java.util.List;

public class RoleDataListener implements ReadListener<SysRole> {


    private static final int BATCH_COUNT = 100;
    private SysRoleService sysRoleService;

    public RoleDataListener(SysRoleService sysRoleService) {
         this.sysRoleService = sysRoleService;
    }


    private List<SysRole> cachedSysRoleList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    /**
     * 这个每一条数据解析都会来调用
     *
     */
    @Override
    public void invoke(SysRole sysRole, AnalysisContext analysisContext) {
        //解析到一条数据进行插入
//        sysRoleService.loadinRoleAdd(sysRole);

        cachedSysRoleList.add(sysRole);
        //插入完之后清空缓存
        if (cachedSysRoleList.size()>=BATCH_COUNT) {
            sysRoleService.loadinRoleMatchAdd(cachedSysRoleList);
            cachedSysRoleList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }




    /**
     * 所有数据解析完成了 都会来调用
     *
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("数据解析成功");
        //剩余的数据开始批量添加
        if (cachedSysRoleList.size()>0) {
            sysRoleService.loadinRoleMatchAdd(cachedSysRoleList);
        }
    }
}
